package other.edan.order;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.api.annotations.RestQueryParam;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEvent;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventRequest;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventResponse;
import com.rkhd.platform.sdk.data.model.Order;
import com.rkhd.platform.sdk.data.model.OrderProduct;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.exception.XsyHttpException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.BatchOperateResult;
import com.rkhd.platform.sdk.model.OperateResult;
import other.edan.order.utils.HCXObjectService;
import other.edan.order.utils.TfReturnMsgTools;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**功能描述：意向合同审批通过后，生成内部订单
 * @ClassName: IntentionConractAfterApproval
 * @Description:
 * @author 范伟绵
 * @date 2024年12月23日
 */

@RestApi(baseUrl = "/xsy/edan")
public class IntentionConractAfterApproval implements ApprovalEvent {
	private final static Logger LOGGER = LoggerFactory.getLogger();
	private final static String LOG_MSG_EX="意向合同审批通过后，生成内部订单:";

	public ApprovalEventResponse execute(ApprovalEventRequest request) throws ScriptBusinessException {
		Long id = request.getDataId();
		request.getEntityApiKey();
		LOGGER.info(LOG_MSG_EX + "开始，数据ID:"+id);
		
		ApprovalEventResponse response = new ApprovalEventResponse();
		try {
			response= handler(id);
		} catch (Exception e) {
			response= TfReturnMsgTools.getApprResponse(false, LOG_MSG_EX + "失败.");
			LOGGER.error(LOG_MSG_EX +"发生异常"+e.getMessage());
			return response;
		}
		LOGGER.info(LOG_MSG_EX + "结束");
		return response;
	}
	
	@RestMapping(value = "/generateInnerOrder", method = RequestMethod.POST)
	public String generateInnerOrder(@RestQueryParam(name="id") String id)  {
		LOGGER.info(LOG_MSG_EX+"执行了按钮事件");
		try{
			ApprovalEventResponse response= handler(Long.valueOf(id));
			return TfReturnMsgTools.getJsonResult(response.getSuccess(),response.getMsg());
		}catch (Exception e){
			LOGGER.error("生成【内部订单】发生异常:"+e.getMessage());
			return TfReturnMsgTools.getExceptionResult("生成【内部订单】失败，请联系管理员！");
		}
	}
	
	/*功能描述：生成内部订单
	 * id：单据ID
	 */
	@SuppressWarnings("unchecked")
	public ApprovalEventResponse handler(Long scrOrderId) throws ApiEntityServiceException, IOException, XsyHttpException {
		String returnMsgString= "获取【意向合同】信息失败";
		
		//获取【意向合同】信息
		Order order=new Order();
		order.setId(scrOrderId);
		order= HCXObjectService.get(order);
		if(null==order) {
			LOGGER.error(returnMsgString);
			return TfReturnMsgTools.getApprResponse(false, returnMsgString);
		}
		LOGGER.info("【意向合同】信息:"+order.toString());

		//获取【订单明细】信息
		String sqlString="Select id from orderProduct where orderId="+scrOrderId;
		List<OrderProduct> orderProductList=HCXObjectService.queryAll(sqlString);
		if(orderProductList.size()<=0) {
			//没有明细
			LOGGER.info("没有【订单明细】信息");
			return TfReturnMsgTools.getApprResponse(false, "没有【订单明细】.");
		}
		LOGGER.info("【订单明细】信息:"+orderProductList.toString());

		//生成【内部订单】
		Order newOrder=order;
		newOrder.setId(null);
		newOrder.setEntityType(3597050965433009L);
		OperateResult insertResult = HCXObjectService.insert(newOrder);
		if(!insertResult.getSuccess()) {
			LOGGER.info("生成【内部订单】失败:"+insertResult.getErrorMessage());
			return TfReturnMsgTools.getApprResponse(false, "生成【内部订单】失败:"+insertResult.getErrorMessage());
		}
		Long targetOrderId=insertResult.getDataId();
		LOGGER.info("【内部订单】Id="+targetOrderId);

		//复制订单明细
		JSONObject copyProductResult=HCXObjectService.copyOrderProduct(scrOrderId,targetOrderId);

		//将软件产品的价格汇总到硬件产品上
		sqlString="select id,parentLine,unitPrice,ruanJian__c from orderProduct where orderId="+scrOrderId;
		List<OrderProduct> softwareOrderProductList=HCXObjectService.queryAll(sqlString);
		if(softwareOrderProductList.isEmpty()) {
			LOGGER.info("获取【订单明细】失败");
			return TfReturnMsgTools.getApprResponse(false, "获取【订单明细】失败。");
		}

		Map<Long,Double> parentLineIdPrice=new HashMap<>();		//父产品（硬件产品）Id，价格
		for(OrderProduct orderProduct:softwareOrderProductList) {
			parentLineIdPrice.put(orderProduct.getId(),orderProduct.getUnitPrice());
		}

		//汇总软件产品价格到硬件产品
		List<OrderProduct> updateOrderProductList=new ArrayList<>();
		for(OrderProduct orderProduct:softwareOrderProductList) {
			if(null==orderProduct.getRuanJian__c() || 2==orderProduct.getRuanJian__c()){
				//不是软件产品
				LOGGER.info("不是软件产品");
				continue;
			}

			//软件产品
			OrderProduct softupdateOrderProduct=new OrderProduct();
			softupdateOrderProduct.setId(orderProduct.getId());
			softupdateOrderProduct.setUnitPrice(0.0);			//软件产品价格为0
			updateOrderProductList.add(softupdateOrderProduct);

			//硬件产品
			OrderProduct hardwareUpdateOrderProduct=new OrderProduct();
			hardwareUpdateOrderProduct.setId(orderProduct.getParentLine());
			BigDecimal softwareUnitPrice=new BigDecimal(orderProduct.getUnitPrice());								//软件价格
			BigDecimal hardwareUnitPrice=new BigDecimal(parentLineIdPrice.get(orderProduct.getParentLine()));		//硬件价格
			hardwareUpdateOrderProduct.setUnitPrice(softwareUnitPrice.add(hardwareUnitPrice).doubleValue());
			updateOrderProductList.add(hardwareUpdateOrderProduct);
		}

		LOGGER.info("更新【内部订单】信息:"+updateOrderProductList.toString());

		//TEST
		/*for(OrderProduct orderProduct:updateOrderProductList) {
			HCXObjectService.insert(orderProduct);
		}*/
		//END TEST

		boolean result=true;
		if(!updateOrderProductList.isEmpty()) {
			BatchOperateResult batchOperateResult=HCXObjectService.updateBatch(updateOrderProductList);
			LOGGER.info("批量插入结果:"+batchOperateResult.getErrorMessage());
			result=batchOperateResult.getSuccess();
		}
		returnMsgString=(result)?"下推【内部订单】成功":"下推【内部订单】失败";
		LOGGER.info("handler 结束,"+returnMsgString);
		return TfReturnMsgTools.getApprResponse(result, returnMsgString);
	}

	public static void main(String[] args) throws IOException, ApiEntityServiceException, XsyHttpException {
		IntentionConractAfterApproval api=new IntentionConractAfterApproval();
		api.handler(3607383575632539L);
	}
}